<template>
    <view class="container">
        <Wave></Wave>
        {{ angle }}
        <canvas id="fishingRod" type="2d" class="fishing-canvas"></canvas>
    </view>
</template>

<script>
import Wave from './lake/wave.vue'
export default {
    props: {
        originAngle: {
            type: Number,
            default: 0
        }
    },
    components: { Wave },

    data() {
        return {
            canvas: null,
            ctx: null,

            // 🎣 鱼竿参数
            angle: 0.11,
            baseTilt: -0.01,
            bendAmount: 0.05,
            rodLength: 380,

            // 🌊 波纹参数
            rippleRadius: 0,
            rippleOpacity: 1,
            rippleAnimating: true,

            // 🪝 鱼线参数（优化上下位置到屏幕中间）
            lineEndX: 0,
            lineEndY: 0,
            targetLineEndX: 0,
            targetLineEndY: 0,
            damping: 0.3,
            lineLength: 200,
            baseLineY: 0, // 改为动态计算，定位到屏幕中间偏下

            imgPath: '',
            fishList: [],
            screenWidth: 0,
            screenHeight: 0,
            collisionFishId: -1,
            lineStartX: 0,
            lineStartY: 0
        };
    },
    methods: {
        /* ========== 🖌️ Canvas 初始化 ========== */
        initCanvas() {
            const info = uni.getSystemInfoSync();
            const { screenWidth, screenHeight, pixelRatio } = info;
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
            // 核心调整：将鱼线Y轴基准设为屏幕高度的 55%（中间偏下，更靠屏幕中间）
            this.baseLineY = screenHeight * 0.65;

            const query = uni.createSelectorQuery().in(this);
            query.select("#fishingRod").node().exec(async (res) => {
                const canvas = res[0].node;
                const ctx = canvas.getContext("2d");
                canvas.width = screenWidth * pixelRatio;
                canvas.height = screenHeight * pixelRatio;
                ctx.scale(pixelRatio, pixelRatio);
                ctx.imageSmoothingEnabled = true;

                this.canvas = canvas;
                this.ctx = ctx;

                this.calcLineTargetPos();
                this.lineEndX = this.targetLineEndX;
                this.lineEndY = this.targetLineEndY;

                this.drawScene();
                this.animateRipple();
            });
        },

        /* ========== 🧮 计算鱼线目标位置 ========== */
        calcLineTargetPos() {
            const { baseTilt, angle, lineLength, baseLineY } = this;
            const baseX = this.screenWidth / 2 + 70;
            const baseY = this.screenHeight - 70;
            const realAngle = baseTilt + angle;

            this.lineStartX = baseX + this.rodLength * Math.sin(realAngle);
            this.lineStartY = baseY - 300;

            // 鱼线终点Y轴固定在中间基准线，X轴跟随角度
            const angleInfluence = angle * 2;
            this.targetLineEndX = this.lineStartX + lineLength * Math.cos(angleInfluence);
            this.targetLineEndY = baseLineY; // 上下位置固定在屏幕中间

            this.targetLineEndX = Math.max(80, Math.min(this.screenWidth - 80, this.targetLineEndX));
        },

        /* ========== 🧭 清空画布 ========== */
        clearCanvas() {
            const { ctx } = this;
            ctx.clearRect(0, 0, this.screenWidth, this.screenHeight);
        },

        /* ========== 🎋 绘制鱼竿 ========== */
        drawRod() {
            const ctx = this.ctx;
            const { baseTilt, angle, bendAmount } = this;
            const baseX = this.screenWidth / 2 + 70;
            const baseY = this.screenHeight - 70;
            const realAngle = baseTilt + angle;

            const endX = baseX + this.rodLength * Math.sin(realAngle);
            const endY = baseY - 300;
            const ctrlX = baseX + (this.rodLength / 2) * Math.sin(realAngle + bendAmount);
            const ctrlY = baseY - (this.rodLength / 2) * Math.cos(realAngle + bendAmount);

            const grad = ctx.createLinearGradient(baseX, baseY, endX, endY);
            grad.addColorStop(0, "#f0f0f0");
            grad.addColorStop(0.3, "#6b5b48");
            grad.addColorStop(1, "#111");

            ctx.beginPath();
            ctx.moveTo(baseX + 30, baseY);
            ctx.quadraticCurveTo(ctrlX, ctrlY, endX, endY);
            ctx.strokeStyle = grad;
            ctx.lineWidth = 8;
            ctx.lineCap = "round";
            ctx.shadowColor = "rgba(0,0,0,0.3)";
            ctx.shadowBlur = 6;
            ctx.stroke();
            ctx.closePath();

            this.calcLineTargetPos();
        },

        /* ========== 🪝 绘制鱼线 ========== */
        drawLine() {
            const ctx = this.ctx;

            const dx = this.targetLineEndX - this.lineEndX;
            const dy = this.targetLineEndY - this.lineEndY;
            const dynamicDamping = Math.min(this.damping + Math.abs(dx) * 0.001, 0.5);
            this.lineEndX += dx * dynamicDamping;
            this.lineEndY += dy * dynamicDamping;

            ctx.beginPath();
            ctx.moveTo(this.lineStartX, this.lineStartY);
            ctx.lineTo(this.lineEndX, this.lineEndY);
            ctx.strokeStyle = this.collisionFishId !== -1 ? "rgba(255,0,0,0.8)" : "rgba(220, 240, 255, 0.8)";
            ctx.lineWidth = 2;
            ctx.stroke();

            ctx.beginPath();
            ctx.arc(this.lineEndX, this.lineEndY, 5, 0, 2 * Math.PI);
            ctx.fillStyle = this.collisionFishId !== -1 ? "#ff0000" : "#ffffff";
            ctx.strokeStyle = "#333";
            ctx.lineWidth = 1;
            ctx.fill();
            ctx.stroke();
        },

        /* ========== 🪵 绘制手柄 ========== */
        drawHandle() {
            const ctx = this.ctx;
            const baseX = this.screenWidth / 2 + 70;
            const baseY = this.screenHeight - 70;

            ctx.beginPath();
            ctx.arc(baseX, baseY, 10, 0, Math.PI, false);
            ctx.fillStyle = "rgba(243, 192, 137, 0.9)";
            ctx.fill();
            ctx.strokeStyle = "rgba(180, 120, 80, 1)";
            ctx.stroke();
        },

        /* ========== 🌊 绘制水波 ========== */
        drawRipple() {
            const ctx = this.ctx;
            const { rippleRadius, rippleOpacity } = this;

            ctx.beginPath();
            ctx.ellipse(this.lineEndX, this.lineEndY, rippleRadius, rippleRadius * 0.5, 0, 0, Math.PI * 2);
            ctx.strokeStyle = `rgba(255,255,255,${rippleOpacity})`;
            ctx.lineWidth = 1.5;
            ctx.stroke();
        },

        /* ========== 🚀 水波动画 ========== */
        animateRipple() {
            if (!this.rippleAnimating) return;
            this.rippleRadius += 0.8;
            this.rippleOpacity -= 0.015;
            if (this.rippleOpacity <= 0) {
                this.rippleRadius = 0;
                this.rippleOpacity = 1;
            }
            this.canvas.requestAnimationFrame(this.animateRipple.bind(this));
        },

        /* ========== 🎣 随机数工具 ========== */
        getRandomFloat(min, max) {
            if (min > max) [min, max] = [max, min];
            return Math.random() * (max - min) + min;
        },

        /* ========== 🐠 初始化鱼群（优化上下位置到屏幕中间） ========== */
        initFishList() {
            const total = 10;
            // 鱼群Y轴分布围绕鱼线基准线，上下各30px，更靠屏幕中间
            const fishMinY = this.baseLineY - 30;
            const fishMaxY = this.baseLineY + 30;
            for (let i = 0; i < total; i++) {
                const fish = {
                    id: i,
                    x: this.getRandomFloat(80, this.screenWidth - 80),
                    y: this.getRandomFloat(fishMinY, fishMaxY), // 跟随鱼线位置调整
                    size: Math.random() * 8 + 4,
                    speed: Math.random() * 0.2 + 0.08,
                    direction: Math.random() * 2 * Math.PI,
                    color: `hsl(${Math.random() * 360}, 50%, 50%)`,
                };
                this.fishList.push(fish);
            }
        },

        /* ========== 🐠 绘制鱼群 + 碰撞检测 ========== */
        // 修改 drawFish 方法中的碰撞检测逻辑
drawFish() {
    const { fishList, baseLineY, ctx } = this;
    const minY = baseLineY - 40;
    const maxY = baseLineY + 40;
    // 只在未碰撞状态下才检测新碰撞
    let newCollisionId = this.collisionFishId !== -1 ? this.collisionFishId : -1;

    fishList.forEach(fish => {
        const { id, x, y, size, speed, direction, color } = fish;

        // 计算与鱼线的距离
        const dx = this.lineEndX - x;
        const dy = this.lineEndY - y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 只有在未碰撞状态时，才检测新的碰撞
        if (this.collisionFishId === -1 && distance < size + 5 && newCollisionId === -1) {
            newCollisionId = id;
        }

        // 绘制鱼（保持不变）
        ctx.beginPath();
        ctx.arc(x, y, size, 0, 2 * Math.PI);
        ctx.fillStyle = color;
        ctx.fill();
        if (this.collisionFishId === id) {
            ctx.strokeStyle = "#ff0000";
            ctx.lineWidth = 2;
            ctx.stroke();
        }

        // 运动逻辑（保持不变）
        if (this.collisionFishId === id) {
            // 跟随鱼线移动（带一定缓冲效果）
            fish.x += (this.lineEndX - x);
            fish.y += (this.lineEndY - y);
        } else {
            // 自由游动逻辑
            fish.x += speed * Math.cos(direction);
            fish.y += speed * Math.sin(direction);

            // 边界反弹
            if (x < size || x > this.screenWidth - size || y < minY + size || y > maxY - size) {
                if (x < size || x > this.screenWidth - size) {
                    fish.direction = Math.PI - direction;
                } else {
                    fish.direction = -direction;
                }
                fish.x = Math.max(size, Math.min(this.screenWidth - size, fish.x));
                fish.y = Math.max(minY + size, Math.min(maxY - size, fish.y));
            }
        }
    });

    // 更新碰撞状态（保持不变）
    this.collisionFishId = newCollisionId;
},

        /* ========== 🎬 主循环 ========== */
        drawScene() {
            this.clearCanvas();
            this.drawRod();
            this.drawLine();
            this.drawHandle();
            this.drawRipple();
            this.drawFish();
            this.canvas.requestAnimationFrame(this.drawScene.bind(this));
        },
    },

    async mounted() {
        this.initFishList();
        this.initCanvas();
    },

    onUnload() {
        this.rippleAnimating = false;
    },

    /* ========== 监听 originAngle 变化 ========== */
    watch: {
        originAngle(val) {
            // 计算当前角度与目标角度的差值
            const currentAngle = this.angle;
            const targetAngle = val * 0.5 + 0.05;
            let diff = targetAngle - currentAngle;

            // 处理角度边界问题，确保最短路径过渡
            if (diff > Math.PI) {
                this.angle = currentAngle - (2 * Math.PI - diff);
            } else if (diff < -Math.PI) {
                this.angle = currentAngle + (2 * Math.PI + diff);
            } else {
                this.angle = targetAngle;
            }
        }
    }
};
</script>

<style scoped lang="less">
.container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

.fishing-canvas {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 100;
}
</style>